package com.jushu.storbox;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.adapter.AbsTemplateAdapter;
import com.jushu.storbox.adapter.AbsTemplateAdapter.IViewHolder;
import com.jushu.storbox.callback.IDownloadCallback;
import com.jushu.storbox.callback.IUploadCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.DownloadObject;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.manager.UploadTaskManager;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.task.tqueue.UploadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.FileTypeUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.viewImpl.TranslateView;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class TranslateActivity extends Activity {

	private static final String TAG = TranslateActivity.class.getSimpleName();

	public final static int NOT_BEGIN = 0;
	public final static int TRANSLATE_START = 1;
	public final static int TRANSLATE_PROGRESS = 2;
	public final static int TRANSLATE_SUCCESS = 3;
	public final static int TRANSLATE_FAILED = 4;
	
	private OnClickListener notComplateClickListener = null;
	private OnClickListener hasComplateClickListener = null;
	
	private OnClickListener deleteItemsClickListener = null;
	private OnClickListener selectAllClickListener = null;
	private OnClickListener deSelectAllClickListener = null;
	
	//multi operation list
	private List<TranslateObjectWrapper> operationList = new ArrayList<TranslateObjectWrapper>();
	//ui item list
	private List<TranslateObjectWrapper> wrapperList = new ArrayList<TranslateObjectWrapper>();

	private AbsTemplateAdapter<TranslateObjectWrapper> baseAdapter = null;
	private NotCompletAdapter notCompletAdapter = null;
	private ComplatedTranslateAdapter hasCompletAdapter = null;
	
	private TranslateView translateView = null;
	private Button select_all_translate_items = null;
	private Button deselect_all_translate_items = null;
	private Button select_delete_translate_items = null;
	private TextView translateListId = null;

	private LayoutInflater inflater;
	SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	
	private class TranslateObjectWrapper {
		private Object translateObject;
		private boolean isChecked = false;
		private BashViewHolder viewHolder;
		
		private DownloadTask downloadTask = null;
		private UploadTask uploadTask = null;
		private boolean requestUpdateSync = false;
		private IDownloadCallback callback = new IDownloadCallback() {

			@Override
			public void onStart() {
				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_START);
					msg.sendToTarget();
				}
			}

			@Override
			public void onFailure(Throwable t, int statusCode) {
				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_FAILED);
					msg.obj = t;
					msg.sendToTarget();
				}
			}

			@Override
			public void onSuccess() {
				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_SUCCESS);
					msg.sendToTarget();
				}
			}

			@Override
			public void onProgress(int currentProgress, long currentSize,
					long maxSize) {

				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_PROGRESS);
					msg.arg1 = currentProgress;
					msg.sendToTarget();
				}
			}

			@Override
			public void onStop() {
				
			}

			@Override
			public void onCanceled() {
				
			}

			@Override
			public void onDettach() {
				
			}
			
		};
		
		private IUploadCallback uploadCallback = new IUploadCallback() {

			@Override
			public void onStart() {

				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_START);
					msg.sendToTarget();
				}
			}

			@Override
			public void onFailure(Throwable t) {

				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_FAILED);
					msg.obj = t;
					msg.sendToTarget();
				}
			}

			@Override
			public void onSuccess(FileInfoResponseV2 successItem) {
				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_SUCCESS);
					msg.sendToTarget();
				}
				
			}

			@Override
			public void onProgress(int currentProgress, long currentSize,
					long maxSize) {
				if(viewHolder != null) {
					Message msg = viewHolder.getHandler().obtainMessage(TRANSLATE_PROGRESS);
					msg.arg1 = currentProgress;
					msg.sendToTarget();
				}
			
			}

			@Override
			public void onStop() {
			}

			@Override
			public void onCanceled() {
			}

			@Override
			public void onDettach() {
			}
			
		};
		
		public TranslateObjectWrapper() {
			LogUtil.e(TAG,"get null Wrapper!");
		}
		
		public TranslateObjectWrapper(Object translateObject, boolean isChecked) {
			this.setTranslateObject(translateObject);
			this.changeCheckState(isChecked);
		}

		public boolean isChecked() {
			return isChecked;
		}
		
		public void changeCheckState(boolean newState) {
			if(isChecked == newState) {
				return;
			}
			boolean containsThis = operationList.contains(this);
			if(newState) {
				if(!containsThis) {
					operationList.add(this);
				} else {
					LogUtil.e(TAG,"error check status");
				}
			} else {
				if(containsThis) {
					operationList.remove(this);
				} else {
					LogUtil.e(TAG,"error check status");
				}
			}
			this.isChecked = newState;
		}

		public Object getTranslateObject() {
			return translateObject;
		}

		public void setTranslateObject(Object translateObject) {
			this.translateObject = translateObject;
		}
		
		public BashViewHolder getViewHolder() {
			return viewHolder;
		}
		
		public void setViewHolder(BashViewHolder viewHolder) {
			this.viewHolder = viewHolder;
		}
		
		public void deleteRecordFromDatabase() {
			if(translateObject instanceof UploadObject) {
				UploadObject uploadObj = (UploadObject) translateObject;
				DAOFactory.instance(getContext()).getUploadFileDao().deleteFile(uploadObj.getId(), uploadObj.getOwnerBy());
			} else if(translateObject instanceof DownloadObject) {
				DownloadObject fileInfo = (DownloadObject) translateObject;
				DAOFactory.instance(getContext()).getDownloadFileDao().deleteFile(fileInfo.getId(),fileInfo.getOwnerId());
			} else {
				
			}
		}
	
		public void stopTranslateTask() {
			if(translateObject instanceof UploadObject && uploadTask != null) {
				uploadTask.stopUploadTask();
				uploadTask = null;
			} else if(translateObject instanceof DownloadObject && downloadTask != null) {
				downloadTask.stopDownloadTask();
				downloadTask = null;
			} else {
				
			}
		}
		
		public void cancelTranslateTask() {
			if(translateObject instanceof UploadObject && uploadTask != null) {
				uploadTask.cancelUploadTask();
				uploadTask = null;
			} else if(translateObject instanceof DownloadObject && downloadTask != null) {
				downloadTask.cancelDownloadTask();
				downloadTask = null;
			} else {
				
			}
		}

		public DownloadTask getNewDownloadTask() {
			if( downloadTask == null) {
				DownloadObject downloadObj = (DownloadObject) translateObject;
				downloadTask = new DownloadTask(getContext(), 0, callback, downloadObj, requestUpdateSync);
			}
			return downloadTask;
		}

		public UploadTask getNewUploadTask() {
			if(uploadTask == null) {
				UploadObject uploadObj = (UploadObject) translateObject;
				uploadTask = new UploadTask(getContext(), uploadObj.getParent(), uploadObj.getLoctPath(), uploadCallback);
			}
			return uploadTask;
		}

		
		public void setRequestSync(boolean requestUpdateSync) {
			this.requestUpdateSync = requestUpdateSync;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		inflater = LayoutInflater.from(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_translate_main_view);
		translateView = (TranslateView) findViewById(R.id.translate_compent);
		select_all_translate_items = (Button) findViewById(R.id.select_all_translate_items);
		deselect_all_translate_items = (Button) findViewById(R.id.deselect_all_translate_items);
		select_delete_translate_items = (Button) findViewById(R.id.select_delete_translate_items);
		translateListId = (TextView) findViewById(R.id.translateListBackId);
		initListener();
		displayHasComplateFragment();
	}
	
	private Context getContext() {
		return TranslateActivity.this;
	}
	
	private void initListener() {
		notComplateClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				displayNotComplateFragment();
			}
		};
		translateView.setTranslateClickListener(notComplateClickListener);
		hasComplateClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				displayHasComplateFragment();
			}
		};
		translateView.setComplateClickListener(hasComplateClickListener);
		
		deleteItemsClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (baseAdapter != null) {
					Iterator<TranslateObjectWrapper> it = operationList.iterator();
					while (it.hasNext()) {
						TranslateObjectWrapper translateObjectWrapper = it.next();

						if (baseAdapter instanceof NotCompletAdapter) {
							translateObjectWrapper.cancelTranslateTask();
						}
						translateObjectWrapper.deleteRecordFromDatabase();

						wrapperList.remove(translateObjectWrapper);
					}

					operationList.clear();
					baseAdapter.notifyDataSetChanged();
				} else {
					LogUtil.e(TAG, "delete operation occured error!");
				}
			}
		};
		select_delete_translate_items.setOnClickListener(deleteItemsClickListener);
		
		selectAllClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				operationList.clear();		
				Iterator<TranslateObjectWrapper> it = wrapperList.iterator();
				while(it.hasNext()) {
					TranslateObjectWrapper wrapperObj = it.next();
					wrapperObj.changeCheckState(true);
				}
				baseAdapter.notifyDataSetChanged();
			}
		};
		select_all_translate_items.setOnClickListener(selectAllClickListener);
		deSelectAllClickListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Iterator<TranslateObjectWrapper> it = wrapperList.iterator();
				while(it.hasNext()) {
					TranslateObjectWrapper wrapperObj = it.next();
					wrapperObj.changeCheckState(false);
				}
				operationList.clear();
				baseAdapter.notifyDataSetChanged();
			}
		};
		deselect_all_translate_items.setOnClickListener(deSelectAllClickListener);
		translateListId.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				TranslateActivity.this.finish();
			}
		});
		
	}

	private void displayNotComplateFragment() {
		if(notCompletAdapter == null) {
			notCompletAdapter = new NotCompletAdapter(wrapperList);
		}
		baseAdapter = notCompletAdapter;
		translateView.setAdapter(baseAdapter);
		
		initTranslateListDateFromDatabase();
		baseAdapter.notifyDataSetChanged();
		translateView.lightUnCompletedBg();
	}

	private void displayHasComplateFragment() {
		if(hasCompletAdapter == null ) {
			hasCompletAdapter  = new ComplatedTranslateAdapter(wrapperList);
		}
		baseAdapter = hasCompletAdapter;
		translateView.setAdapter(baseAdapter);
		
		initComplateListDateFromDatabase();
		baseAdapter.notifyDataSetChanged();
		translateView.lightCompletedBg();
	}
	
	private void initComplateListDateFromDatabase() {
		wrapperList.clear();
		operationList.clear();
		List<UploadObject> uploadList = DAOFactory.instance(this)
				.getUploadFileDao().getComplateUploadFileList();
		if(uploadList != null) {
			for(int i = 0; i < uploadList.size(); i++) {
				TranslateObjectWrapper obj = new TranslateObjectWrapper(uploadList.get(i), false);
				wrapperList.add(obj); 
			}
		}
		
		List<DownloadObject> downloadList = DAOFactory.instance(this)
				.getDownloadFileDao().getComplateDownloadFileList();
		if(downloadList != null) {
			for(int i = 0; i < downloadList.size(); i++) {
				TranslateObjectWrapper obj = new TranslateObjectWrapper(downloadList.get(i),false);
				wrapperList.add(obj); 
			}
		}
		
	}
	
	private void initTranslateListDateFromDatabase() {
		wrapperList.clear();
		operationList.clear();
		List<UploadObject> uploadList = DAOFactory.instance(this)
				.getUploadFileDao().getNotComplateUploadFileList();
		if(uploadList != null) {
			for(int i = 0; i < uploadList.size(); i++) {
				TranslateObjectWrapper obj = new TranslateObjectWrapper(uploadList.get(i),false);
				wrapperList.add(obj); 
			}
		}
		
		List<DownloadObject> downloadList = DAOFactory.instance(this)
				.getDownloadFileDao().getNotComplateDownloadFileList();
		if(downloadList != null) {
			for(int i = 0; i < downloadList.size(); i++) {
				TranslateObjectWrapper obj = new TranslateObjectWrapper(downloadList.get(i),false);
				wrapperList.add(obj);
			}
		}
		
	}
	
	public abstract class BashViewHolder implements IViewHolder<TranslateObjectWrapper>{
		
		int position;
		
		protected int getPosition() {
			return position;
		}
		
		protected void setPosition(int position) {
			this.position = position;
		}
		
		/**content View*/
		protected View contentView;
		protected TranslateObjectWrapper translateObjeWrapper = null;

		public BashViewHolder() {
		}
		
		protected abstract void initListener();
		
		public abstract View getLayoutView(ViewGroup parent);
		public abstract void initViewByHolderDate(TranslateObjectWrapper translateObject);
		
		@Override
		public View getHolderView() {
			return contentView;
		}

		@Override
		public TranslateObjectWrapper getHolderDate() {
			if(translateObjeWrapper == null) {
				translateObjeWrapper = new TranslateObjectWrapper();
				translateObjeWrapper.setViewHolder(this);
			}
			return translateObjeWrapper;
		}
		
		@Override
		public void updataHolderView() {
			
		}

		protected void deleteRecordFromList() {
			TranslateObjectWrapper holderData = getHolderDate();
			setItemSelected(false);
			holderData.deleteRecordFromDatabase();
			wrapperList.remove(holderData);
			holderData.changeCheckState(false);
		}
		
		/**select the record of this translate*/
		protected CheckBox 	translate_item_operation;
		protected boolean isItemSelected() {
			return getHolderDate().isChecked();
		}
		
		protected void setItemSelected(boolean selected) {
			translate_item_operation.setChecked(selected);
		}
		
		public abstract Handler getHandler() ;
	}
	
	private class ComplatedTranslateAdapter extends AbsTemplateAdapter<TranslateObjectWrapper> {
		
		public ComplatedTranslateAdapter(List<TranslateObjectWrapper> translateList) {
			super(translateList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			HasComplateViewHolder holder = null;
			if(convertView == null) {
				holder = new HasComplateViewHolder();
				convertView = holder.getLayoutView(parent);
				convertView.setTag(holder);
			} else {
				holder = (HasComplateViewHolder) convertView.getTag();
			}
			holder.initViewByHolderDate(getItem(position));
			holder.initListener();
			
			return convertView;
		}

		
	}
	
	private class HasComplateViewHolder extends BashViewHolder{
		/**the type icon of translate record*/
		private ImageView 	type_icon;
		/**the name of translate record*/
		private TextView 	translate_file_name;
		/**the download or upload type of translate record*/
		private ImageView 	translate_type_icon;
		/**the date of translate record*/
		private TextView 	translate_file_date;
		/**the size of translate record*/
		private TextView 	translate_file_size;
		/**delete the record of this translate*/
		private ImageView 	delete_translate_item;
	
		private Handler uiUpdateHandler = new Handler();
		
		public HasComplateViewHolder() {
			super();
			type_icon = null;
			translate_file_name = null;
			translate_type_icon = null;
			translate_file_date = null;
			translate_file_size = null;
			delete_translate_item = null;
			translate_item_operation = null;
			contentView = null;
		}
		
		public View getLayoutView(ViewGroup parent) {
			contentView = inflater.inflate(R.layout.activity_translate_finished_item_view, parent, false);
			type_icon = (ImageView) contentView.findViewById(R.id.type_icon);
			translate_file_name = (TextView) contentView.findViewById(R.id.translate_file_name);
			translate_type_icon = (ImageView) contentView.findViewById(R.id.translate_type_icon);
			translate_file_date = (TextView) contentView.findViewById(R.id.translate_file_date);
			translate_file_size = (TextView) contentView.findViewById(R.id.translate_file_size);
			delete_translate_item = (ImageView) contentView.findViewById(R.id.delete_translate_item);
			translate_item_operation = (CheckBox) contentView.findViewById(R.id.translate_item_operation);
			return contentView;
		}
		
		protected void initListener() {
			
			contentView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					TranslateObjectWrapper holderData = getHolderDate();
					holderData.changeCheckState(!holderData.isChecked());
					baseAdapter.notifyDataSetChanged();
				}
			});
			
			delete_translate_item.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					deleteRecordFromList();
					baseAdapter.notifyDataSetChanged();
				}
			});
			
			translate_item_operation.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					TranslateObjectWrapper holderData = getHolderDate();
					holderData.changeCheckState(!holderData.isChecked());
				}
			});
			
		}

		public void initViewByHolderDate(TranslateObjectWrapper wrapperObject) {
			
			Object translateObject = wrapperObject.getTranslateObject();
			if(translateObject instanceof UploadObject) {
				UploadObject innerObj = (UploadObject) translateObject;
				//bindingTypeIcon(innerObj);
				bindingTypeIcon(FileTypeUtil.getDefaultResourceId(innerObj.getName()));
				bindingItemName(innerObj.getName());
				bindingTranslateTypeIcon(R.mipmap.order_up);
				bindingItemDate(innerObj.getSetLastUpdateDate());
				bindingItemSize(innerObj.getSize());
			} else if(translateObject instanceof DownloadObject) {
				DownloadObject innerObj = (DownloadObject) translateObject;
//				bindingTypeIcon(innerObj);
				bindingTypeIcon(FileTypeUtil.getDefaultResourceId(innerObj.getFileName()));
				bindingItemName(innerObj.getFileName());
				bindingTranslateTypeIcon(R.mipmap.order_down);
				bindingItemDate(innerObj.getLastUpdateTime());
				bindingItemSize(innerObj.getFileSize());
			} else {
				LogUtil.e(TAG,"translate object is error type instance");
			}
			
			setItemSelected(wrapperObject.isChecked());
			translateObjeWrapper = wrapperObject;
			wrapperObject.setViewHolder(this);
			
		}

		//===========================================
		private void bindingTypeIcon(UploadObject innerObj) {
			String thumbnailPath = DirectoryUtil.genThumbnailFileFullName(getContext(), innerObj.getOwnerBy(),innerObj.getId(),innerObj.getName());
			File thmbnail = new File(thumbnailPath);
			if(thmbnail.exists()) {//thumbnail image is exists
				bindingTypeIcon(thmbnail);
			} else {
				//oraginal image is exists
				String filePath = DirectoryUtil.generateFileDownloadPath(getContext(), innerObj.getOwnerBy(), innerObj.getId(), innerObj.getName());
				File oldPicturePath = new File(filePath);
				if(oldPicturePath.exists()) {
					bindingTypeIcon(oldPicturePath);
				} else {//no thumbnail image
					bindingTypeIcon(R.mipmap.upload_photo);
				}
			}
		}

		private void bindingTypeIcon(DownloadObject innerObj) {
			String thumbnailpath = DirectoryUtil.genThumbnailFileFullName(getContext(), innerObj.getOwnerBy(),innerObj.getId(),innerObj.getFileName());
			File thmbnailPath = new File(thumbnailpath);
			if(thmbnailPath.exists()) {//thumbnail image is exists
				bindingTypeIcon(thmbnailPath);
			} else {
				//oraginal image is exists
				String filePath = DirectoryUtil.generateFileDownloadPath(getContext(), innerObj.getOwnerBy(), innerObj.getId(), innerObj.getFileName());
				File oldPicturePath = new File(filePath);
				if(oldPicturePath.exists()) {
					bindingTypeIcon(oldPicturePath);
				} else {//no thumbnail image
					bindingTypeIcon(R.mipmap.upload_photo);
				}
			}
		}

		private void bindingTypeIcon(File imageFile) {
			try {
				Bitmap typeIcon = BitmapFactory.decodeFile(imageFile.getCanonicalPath());
				type_icon.setImageBitmap(typeIcon);
			} catch (Exception e) {
				bindingTypeIcon(R.mipmap.upload_photo);
			}
		}
		
		private void bindingTypeIcon(int typeIconRes) {
			type_icon.setImageResource(typeIconRes);
		}

		private void bindingItemName(String name) {
			if(name != null ) {
				translate_file_name.setText(name);
			} else {
				LogUtil.e(TAG,"the istance of name is null");
			}
		}

		private void bindingTranslateTypeIcon(int transIconRes) {
			translate_type_icon.setImageResource(transIconRes);
		}

		private void bindingItemDate(long itemDate) {
			if(itemDate >= 0) {
				translate_file_date.setText(timeDateFormat.format(itemDate));
			} else {
				LogUtil.e(TAG,"the value of date is not correct");
			}
		}

		private void bindingItemSize(long itemSize) {
			if(itemSize >= 0) {
				translate_file_size.setText(PublicTools.changeBKM(String.valueOf(itemSize)));
			} else {
				LogUtil.e(TAG,"the value of size is not correct");
			}
		}
		
		@Override
		public Handler getHandler() {
			return uiUpdateHandler;
		}

	}

	private enum ControlType {
		TRANSLATE, STOP
	}
	
	private class NotComplateViewHolder extends BashViewHolder{
		
		private ImageView type_icon;
		private TextView translate_file_name;
		private ImageView translate_type_icon;
		private TextView translate_file_size;
		private ImageView control_translate_item;
		private ControlType currentControlType;
		private ImageView delete_translate_item;
		private ProgressBar download_progress;
		private int maxProgress = 100;
		private int currentProgress = 0;
		
		@SuppressLint("HandlerLeak")
		private Handler uiUpdateHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
					case TRANSLATE_FAILED:
						download_progress.setProgress(currentProgress);
						baseAdapter.notifyDataSetChanged();
						break;
					case TRANSLATE_PROGRESS:
						download_progress.setProgress(msg.arg1);
						currentProgress = msg.arg1;
						break;
					case TRANSLATE_START:
						download_progress.setProgress(0);
						break;
					case TRANSLATE_SUCCESS:
						setItemSelected(false);
						wrapperList.remove(getHolderDate());
						
						download_progress.setProgress(100);
						baseAdapter.notifyDataSetChanged();
						
						break;
					case NOT_BEGIN:
						break;
					
					default:
						super.handleMessage(msg);
						break;
				}
			}
			
		};
		
		/**content View*/
		
		public NotComplateViewHolder() {
			super();
			type_icon = null;
			translate_file_name = null;
			translate_type_icon = null;
			translate_file_size = null;
			control_translate_item = null;
			delete_translate_item = null;
			translate_item_operation = null;
			currentControlType = ControlType.TRANSLATE;
			contentView = null;
		}
		
		

		public View getLayoutView(ViewGroup parent) {
			contentView = inflater.inflate(R.layout.activity_translate_not_finish_item_view, parent, false);
			type_icon = (ImageView) contentView.findViewById(R.id.type_icon);
			translate_file_name = (TextView) contentView.findViewById(R.id.translate_file_name);
			translate_type_icon = (ImageView) contentView.findViewById(R.id.translate_type_icon);
			translate_file_size = (TextView) contentView.findViewById(R.id.translate_file_size);
			control_translate_item = (ImageView) contentView.findViewById(R.id.control_translate_item);
			delete_translate_item = (ImageView) contentView.findViewById(R.id.delete_translate_item);
			translate_item_operation = (CheckBox) contentView.findViewById(R.id.translate_item_operation);
			download_progress = (ProgressBar) contentView.findViewById(R.id.download_progress);
			return contentView;
		}

		protected void initListener() {
			contentView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					TranslateObjectWrapper holderData = getHolderDate();
					holderData.changeCheckState(!holderData.isChecked());
					baseAdapter.notifyDataSetChanged();
				}
			});
			
			control_translate_item.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					switch(currentControlType) {
					case TRANSLATE:
						currentControlType = ControlType.STOP;
						showControlIcon();
						getHolderDate().stopTranslateTask();
						break;
						
					case STOP:
						startTranslateTask();
						break;
						
					default:
						currentControlType = ControlType.TRANSLATE;
						showControlIcon();
						break;
					}
				}
			});
			
			delete_translate_item.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					getHolderDate().cancelTranslateTask();
					deleteRecordFromList();
					baseAdapter.notifyDataSetChanged();
				}

			});
			
			translate_item_operation.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					TranslateObjectWrapper holderData = getHolderDate();
					holderData.changeCheckState(!holderData.isChecked());
				}
			});
			
		}
		
		public void initViewByHolderDate(TranslateObjectWrapper wrapperObject) {
			
			
			Object translateObject = wrapperObject.getTranslateObject();
			if(translateObject instanceof UploadObject) {
				UploadObject innerObj = (UploadObject) translateObject;
				bindingTypeIcon(FileTypeUtil.getDefaultResourceId(innerObj.getName()));
				bindingItemName(innerObj.getName());
				bindingTranslateTypeIcon(R.mipmap.order_up);
				bindingItemSize(innerObj.getSize());
				bindingControlIcon(wrapperObject, innerObj);
				currentProgress = (int) (innerObj.getCurrentPaogress() * 100 / innerObj.getSize());
				bindingItemProgress();
			} else if(translateObject instanceof DownloadObject) {
				DownloadObject innerObj = (DownloadObject) translateObject;
				bindingTypeIcon(FileTypeUtil.getDefaultResourceId(innerObj.getFileName()));
				bindingItemName(innerObj.getFileName());
				bindingTranslateTypeIcon(R.mipmap.order_down);
				bindingItemSize(innerObj.getFileSize());
				bindingControlIcon(wrapperObject, innerObj );
				currentProgress = (int) (innerObj.getCurrentSize() * 100 / innerObj.getFileSize());
				bindingItemProgress();
			} else {
				LogUtil.e(TAG,"translate object is error type instance");
			}

			setItemSelected(wrapperObject.isChecked());
			translateObjeWrapper = wrapperObject;
			wrapperObject.setViewHolder(this);
		}

		private void bindingControlIcon(TranslateObjectWrapper innerObj, DownloadObject downObj) {
			innerObj.downloadTask = DownloadTaskManager.getTask(downObj.getId());
			if(innerObj.downloadTask != null) {
				innerObj.downloadTask.setCallback(innerObj.callback);
				innerObj.setRequestSync(innerObj.downloadTask.isRequestUpdateSync());
				currentControlType = ControlType.TRANSLATE;
			} else {
				currentControlType = ControlType.STOP;
			}
			showControlIcon();
		}

		private void showControlIcon() {
			switch(currentControlType) {
				case TRANSLATE:
					control_translate_item.setImageResource(R.mipmap.stop_tranlate_task);
					break;
				case STOP:
					control_translate_item.setImageResource(R.mipmap.continue_translate_task);
					break;
				default:
					control_translate_item.setImageResource(R.mipmap.stop_tranlate_task);
					break;
			}
		}

		private void bindingControlIcon(TranslateObjectWrapper wrapper, UploadObject upObj) {
			wrapper.uploadTask = UploadTaskManager.getTask(upObj.getLoctPath());
			
			if(wrapper.uploadTask != null) {
				wrapper.uploadTask.setCallback(wrapper.uploadCallback);
				currentControlType = ControlType.TRANSLATE;
			} else {
				currentControlType = ControlType.STOP;
			}
			showControlIcon();
		}

		private void bindingItemProgress() {
			download_progress.setProgress(currentProgress);
			download_progress.setMax(maxProgress);
		}
		
		private void bindingItemName(String name) {
			if(name != null ) {
				translate_file_name.setText(name);
			} else {
				LogUtil.e(TAG,"the istance of name is null");
			}
		}
		
		private void bindingTypeIcon(UploadObject innerObj) {
			File thmbnailPath = new File("");
			if(thmbnailPath.exists()) {//thumbnail image is exists
				bindingTypeIcon(thmbnailPath);
			} else {
				//oraginal image is exists
				File oldPicturePath = new File("");
				if(oldPicturePath.exists()) {
					bindingTypeIcon(oldPicturePath);
				} else {//no thumbnail image
					bindingTypeIcon(R.mipmap.upload_photo);
				}
			}
		}

		private void bindingTypeIcon(DownloadObject innerObj) {
			File thmbnailPath = new File("");
			if(thmbnailPath.exists()) {//thumbnail image is exists
				bindingTypeIcon(thmbnailPath);
			} else {
				//oraginal image is exists
				File oldPicturePath = new File("");
				if(oldPicturePath.exists()) {
					bindingTypeIcon(oldPicturePath);
				} else {//no thumbnail image
					bindingTypeIcon(R.mipmap.upload_photo);
				}
			}
		}

		private void bindingTypeIcon(File imageFile) {
			try {
				Bitmap typeIcon = BitmapFactory.decodeFile(imageFile.getCanonicalPath());
				type_icon.setImageBitmap(typeIcon);
			}catch (Exception e) {
				bindingTypeIcon(R.mipmap.upload_photo);
			}
		}
		
		private void bindingTypeIcon(int typeIconRes) {
			type_icon.setImageResource(typeIconRes);
		}

		private void bindingTranslateTypeIcon(int transIconRes) {
			translate_type_icon.setImageResource(transIconRes);
		}

		private void bindingItemSize(long itemSize) {
			if(itemSize >= 0) {
				translate_file_size.setText(PublicTools.changeBKM(String.valueOf(itemSize)));
			} else {
				LogUtil.e(TAG,"the value of size is not correct");
			}
		}

		private void startTranslateTask() {
			Object translate = getHolderDate().getTranslateObject();
			if(translate instanceof UploadObject) {
				startUploadTaskWithCheckNetwork();
			} else if(translate instanceof DownloadObject) {
				startDownloadTaskWithCheckNetwork();
			} else {
			}
		}
		
		private void startUploadTaskWithCheckNetwork() {
			WifiController wifiController = ShareDriveApplication.getInstance().getWifiController();
			if (!wifiController.getNetworkState()) {
                Toast.makeText(getContext(),R.string.clouddrive_mode_without_internet,
                    Toast.LENGTH_SHORT).show();
            } else {
            	if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType())
                    || !PublicTools.getDownloadRemind(getContext())) {
                	doStartUploadTask();
                } else {
                    final ClouddriveDialog menuDialog = new ClouddriveDialog(getContext(),
                        R.style.myDialogTheme, R.layout.window_wifi_dialog);
                    menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
                    menuDialog.setWidth(LayoutParams.MATCH_PARENT);
                    menuDialog.setCanceledOnTouchOutside(true);
                    menuDialog.show();
                    View conventView = menuDialog.getConventView();
                    Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);
                    
                    confirmBt.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        	doStartUploadTask();
                        }
                    });
                    Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
                    cancleBt.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            menuDialog.dismiss();
                        }
                    });
                }
            }
		}
		
		private void startDownloadTaskWithCheckNetwork() {
			WifiController wifiController = ShareDriveApplication.getInstance().getWifiController();
			if (!wifiController.getNetworkState()) {
                Toast.makeText(getContext(),R.string.clouddrive_mode_without_internet,
                    Toast.LENGTH_SHORT).show();
            } else {
            	if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType())
                    || !PublicTools.getDownloadRemind(getContext())) {
            		doStartDownloadTask();
                } else {
                    final ClouddriveDialog menuDialog = new ClouddriveDialog(getContext(),
                        R.style.myDialogTheme, R.layout.window_wifi_dialog);
                    menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
                    menuDialog.setWidth(LayoutParams.MATCH_PARENT);
                    menuDialog.setCanceledOnTouchOutside(true);
                    menuDialog.show();
                    View conventView = menuDialog.getConventView();
                    Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);
                    
                    confirmBt.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        	doStartDownloadTask();
                        }
                    });
                    Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
                    cancleBt.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            menuDialog.dismiss();
                        }
                    });
                }
            }
		}
		
		private void doStartUploadTask() {
			currentControlType = ControlType.TRANSLATE;
			showControlIcon();
			
			UploadObject uploadObj = (UploadObject) getHolderDate().getTranslateObject();
			File file = new File(uploadObj.getLoctPath());
			if(file.exists()) {
				UploadTaskManager.addTask(getHolderDate().getNewUploadTask());
			} else {
				Toast.makeText(getContext(), uploadObj.getLoctPath(), Toast.LENGTH_SHORT).show();
			}
			baseAdapter.notifyDataSetChanged();
		}
		
		private void doStartDownloadTask() {
			currentControlType = ControlType.TRANSLATE;
			showControlIcon();
			
			DownloadTaskManager.addTask(getHolderDate().getNewDownloadTask());
			baseAdapter.notifyDataSetChanged();
		}

		@Override
		public Handler getHandler() {
			return uiUpdateHandler;
		}
	}
	
	private class NotCompletAdapter extends AbsTemplateAdapter<TranslateObjectWrapper> {

		public NotCompletAdapter(List<TranslateObjectWrapper> translateList) {
			super(translateList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			NotComplateViewHolder holder = null;
			if(convertView == null) {
				holder = new NotComplateViewHolder();
				convertView = holder.getLayoutView(parent);
				convertView.setTag(holder);
			} else {
				holder = (NotComplateViewHolder) convertView.getTag();
			}
			TranslateObjectWrapper holderDate = getItem(position);
			holder.initListener();
			holder.initViewByHolderDate(holderDate);
			
			return convertView;
		}
		
	}
}
